package com.chenfan.ccp.plug.rpc.util;

import com.alibaba.ttl.TransmittableThreadLocal;
import feign.Request;

import java.util.concurrent.TimeUnit;

public class RpcConfigUtil {

    public static long TIME_OUT_MILLISECONDS = 1000 * 90;

    //这里设置全局的统一超时时常
    private static ThreadLocal<Request.Options> optionsLocal = new TransmittableThreadLocal();

    private RpcConfigUtil() {

    }

    public static Request.Options getDefaultsOptions() {
        return new Request.Options(90, TimeUnit.SECONDS, 90, TimeUnit.SECONDS, true);
    }

    /**
     * @param connectTimeout     连接时间.
     * @param connectTimeoutUnit 连接的单位
     * @param readTimeout        超时时间.
     * @param readTimeoutUnit    超时单位.
     * @param followRedirects    是否允许重定向
     */
    public static void setOnceTime(long connectTimeout, TimeUnit connectTimeoutUnit, long readTimeout, TimeUnit readTimeoutUnit, boolean followRedirects) {
        Request.Options options = new Request.Options(connectTimeout, connectTimeoutUnit, readTimeout, readTimeoutUnit, followRedirects);
        optionsLocal.set(options);
    }

    /**
     * @param connectTimeout 连接时间.
     * @param readTimeout    超时时间.
     */
    public static void setOnceTimeBySecond(long connectTimeout, long readTimeout) {
        Request.Options options = new Request.Options(connectTimeout, TimeUnit.SECONDS, readTimeout, TimeUnit.SECONDS, true);
        optionsLocal.set(options);
    }

    /**
     * @param connectTimeout 连接时间.
     * @param readTimeout    超时时间.
     */
    public static void setOnceTimeByMilliseconds(long connectTimeout, long readTimeout) {
        Request.Options options = new Request.Options(connectTimeout, TimeUnit.MILLISECONDS, readTimeout, TimeUnit.MILLISECONDS, true);
        optionsLocal.set(options);
    }

    public static Request.Options getOptions() {

        return optionsLocal.get();
    }

    public static void remove() {

        if (optionsLocal.get() == null) {
            return;
        }
        optionsLocal.remove();
    }
}
